package com.conversationboard.model;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import com.conversationboard.cache.ThreadTitleCache;
import com.conversationboard.database.Database;
import com.conversationboard.database.Queries;

public class Bookmark {

	private String title;
	private int boardId;
	private int threadId;
	private int messageId;


	public boolean isUpdated() {

		int latestMessageId = ThreadTitleCache.getLatestMessageId(this.boardId, this.threadId);

		boolean isUpdated = (latestMessageId > this.messageId); 
		
		return isUpdated;
		
	}


	public int getBoardId() {
		return boardId;
	}


	public void setBoardId(int boardId) {
		this.boardId = boardId;
	}


	public int getMessageId() {
		return messageId;
	}


	public void setMessageId(int messageId) {
		this.messageId = messageId;
	}


	public int getThreadId() {
		return threadId;
	}


	public void setThreadId(int threadId) {
		this.threadId = threadId;
	}


	public String getTitle() {
		return title;
	}


	public void setTitle(String title) {

		if (title == null) {
			this.title = "<strong>[This bookmark is no longer valid. The thread may have been moved to a different board]</strong>";
			return;
		}

		this.title = title;
	}


	public void insert(int userId) throws SQLException {

		Connection connection = null;

		try {

			connection = Database.getConnection();

			PreparedStatement statement = connection.prepareStatement(Queries.INSERT_BOOKMARK);
			statement.setInt(1, userId);
			statement.setInt(2, this.getBoardId());
			statement.setInt(3, this.getThreadId());
			statement.setInt(4, this.getMessageId());

			statement.executeUpdate();

		} finally {
			Database.close(connection);
		}
	}


	public void update(Connection connection, int userId) throws SQLException {

		boolean newConnection = (connection == null);

		try {

			if (newConnection) {
				connection = Database.getConnection();
			}

			PreparedStatement statement = connection.prepareStatement(Queries.UPDATE_BOOKMARK);
			statement.setInt(1, this.getMessageId());
			statement.setInt(2, userId);
			statement.setInt(3, this.getBoardId());
			statement.setInt(4, this.getThreadId());

			statement.executeUpdate();

		} finally {
			if (newConnection) {
				Database.close(connection);
			}
		}
	}

}
